package com.mvp.shq.washer.ui.home;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.MyViewPagerAdapter;
import com.mvp.shq.washer.base.BaseFragment;
import com.mvp.shq.washer.entity.Banner;
import com.mvp.shq.washer.entity.OrderInfo;
import com.mvp.shq.washer.entity.Washer;
import com.mvp.shq.washer.entity.result.WasherInfoResult;
import com.mvp.shq.washer.http.RxSchedulers;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.rxbus.ThreadMode;
import com.mvp.shq.washer.utils.DateUtils;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.view.widget.LoopViewPager;
import com.mvp.shq.washer.view.widget.ShapedImageView;
import com.mvp.shq.washer.view.widget.WaveView;
import com.mvp.shq.washer.zbar.ZbarActivity;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.reactivestreams.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;



@RuntimePermissions
public class HomeFragment extends BaseFragment<HomePresenter, HomeModel> implements HomeConstract.View {

    @BindView(R.id.viewpager)
    LoopViewPager vp;
    @BindView(R.id.home_bg)
    AutoLinearLayout homeBg;
    @BindView(R.id.img_scan_state)
    ImageView imgScanContent;
    @BindView(R.id.img_scan)
    ImageButton imgScan;
    @BindView(R.id.wave_view)
    WaveView waveView;
    @BindView(R.id.arl_wave)
    AutoRelativeLayout arlWave;
    @BindView(R.id.tv_washer_finish_time)
    TextView tvFinishTime;
    @BindView(R.id.tv_time)
    TextView tvRestTime;
    private List<Banner> mList;
    private MyViewPagerAdapter adapter;
    private int bannerPosition;
    private CountDownTimer timer;
    private CountDownTimer washerTimer;
    private double washerTotalTime = 0;
    private double washerProgressTime = 1;
    private String orderNo;
    private int FRAGMENT_STATUS = 0;
    private Observable<Long> washerObservable;
    private Disposable washerDisposable;
    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(getActivity(), getResources().getColor(R.color.home_status_bar), 0);
        setWasherTimer();
        //presenter.banner();
        initBanner();
        presenter.getOrderInfo();
    }

    @Subscribe(code = EventCode.UPDATE_BANNER,threadMode = ThreadMode.MAIN)
    public void initBanner(){
        getBannerSuccess(SpUtil.getBanner());
    }

    @OnClick({R.id.img_scan,R.id.wave_view,R.id.arl_wave})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.img_scan:
                if (SpUtil.getUser() == null){
                    JumpUtil.toLogin(context);
                    return;
                }
                HomeFragmentPermissionsDispatcher.toScanWithCheck(this);
                break;
            case R.id.wave_view:
                break;
        }
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    public void toScan() {
//        Intent intent = new Intent(context, CaptureActivity.class);
//        startActivityForResult(intent, 7);
        Intent intent = new Intent(context, ZbarActivity.class);
        startActivityForResult(intent,7);
    }
    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(context)
                .setMessage("是否开启相机权限")
                .setPositiveButton("同意", (dialog, button) -> request.proceed())
                .setNegativeButton("拒绝", (dialog, button) -> request.cancel())
                .show();
        Toast.makeText(context, "showRationaleForCamera", Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(context, "拒绝相机权限将无法使用扫码功能", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void showNeverAskForCamera() {
        Toast.makeText(context, "关闭相机权限无法使用扫码功能，请先允许相机", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        HomeFragmentPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ZbarActivity.RESULT_CODE_QR_SCAN && requestCode == 7) { //RESULT_OK = -1
            Bundle bundle = data.getExtras();
            Log.d("zing", "扫码返回:" + bundle.toString());
            String scanResult = bundle.getString(ZbarActivity.INTENT_EXTRA_KEY_QR_SCAN);
            Logger.d("扫码结果:"+scanResult);
            scanResult(scanResult);
        }
    }

    private void scanResult(String result){
        try {
            Map<String,String> map = StringUtils.URLRequest(result);
            String washerNo = map.get("washerno");
            Logger.d("washerNo:"+washerNo);
            if (TextUtils.isEmpty(washerNo) || washerNo.equals("")){
                T.show("无效二维码");
            }else {
                //T.show("洗衣机编号为："+washerNo);
                //showLoadingDialog(true);
//                Washer washer = new Washer();
//                washer.setWasherNo(washerNo);
//                presenter.getWasherInfo(washer);
                JumpUtil.toOrderConfirm(context,washerNo);
            }
//            Gson gson = new Gson();
//            Washer washer = gson.fromJson(result,Washer.class);
//            if (washer == null || washer.getWasherNo() == null){
//                T.show("二维码有误");
//            }else {
//                Logger.d("扫码返回no:"+washer.getId() + "洗衣机类型:"+washer.getWasherType());
//                showLoadingDialog(true);
//                presenter.getWasherInfo(washer);
//            }
        }catch (Exception e){
            e.printStackTrace();
            T.show("二维码错误");
        }

    }

    @Override
    public void getBannerSuccess(List<Banner> banners) {
        if (banners != null && banners.size()>0){
            mList = new ArrayList<>();
            mList.addAll(banners);
            //vp.setPageTransformer(true,new RotationPageTransformer());
            adapter = new MyViewPagerAdapter(context, mList);
            vp.setAdapter(adapter);
            vp.setOffscreenPageLimit(3);
            vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    bannerPosition = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            adapter.notifyDataSetChanged();
            bannerPosition = vp.getCurrentItem();
            if (timer != null){
                timer.onFinish();
                timer.cancel();
                timer = null;
                initTimer();
            }
        }

    }

    public void initTimer(){
        if (timer == null){
            long TIME_SPACE = 1000;
            long ALL_TIME = 24 * 60 * 60 * TIME_SPACE;
            timer = new CountDownTimer(ALL_TIME,3000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    if (FRAGMENT_STATUS == 0){
                        setBanner();
                    }
                }

                @Override
                public void onFinish() {

                }
            };
            timer.start();
        }
    }

    @Override
    public void onPause() {
        if (timer != null){
            timer.onFinish();
            timer.cancel();
            timer = null;
        }
        FRAGMENT_STATUS = 1;
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        FRAGMENT_STATUS = 0;
        initTimer();
    }

    @Override
    public void onDestroy() {
        if (timer != null){
            timer.onFinish();
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

    @Override
    public void getBannerFail(String msg) {
        Logger.d("获取banner失败:"+msg);
    }

    @Override
    public void getWasherInfoS(WasherInfoResult result) {
        //JumpUtil.toOrderConfirm(context,re sult);
    }

    @Override
    public void setBanner() {
        if (vp == null){
            return;
        }
        if (mList == null || mList.size() <= 0){
            return;
        }
        try{
            vp.setCurrentItem(bannerPosition);
        }catch (Exception e){
            e.printStackTrace();
        }
        bannerPosition ++;
    }
    //后台推送订单时间，修改进行中的时间
    @Subscribe(code = EventCode.UPDATE_WASHER_TIME)
    public void updateTime(Integer time){
        Logger.d("修改进行中的订单的时间:"+time);
        //T.show("收到推送时间:"+time);
        OrderInfo order = SpUtil.getOrder();
        if (order == null){
            return;
        }
        order.setRestTime(time);
        SpUtil.setOrder(order);
//        washerTotalTime = order.getPatternTime();
//        washerProgressTime = washerTotalTime - time;
//        waveView.change(washerProgressTime/washerTotalTime);
//        tvRestTime.setText(time+"");
        setWasherTimer();
    }
    //当前有正在进行中的订单，显示水球
    @Override
    public void hasOrder(OrderInfo orderInfo) {
        OrderInfo order = SpUtil.getOrder();
        orderNo = orderInfo.getOrderNo();
        if (order != null){
            orderInfo.setRestTime(order.getRestTime());
        }
//        if (order.getProgressTime() == 0 && order.getRestTime() == 0){
//            //订单刚开始
//            orderInfo.setProgressTime(0);
//            orderInfo.setRestTime(order.getPatternTime());
//        }
        SpUtil.setOrder(orderInfo);
        setWasherTimer();
//        washerProgressTime = order.getProgressTime();
//        waveView.change(washerProgressTime/washerTotalTime);
//        tvRestTime.setText(order.getRestTime()+"");
    }

    @Override
    public void notOrder() {
        washerTotalTime = 0;
        washerProgressTime = 1;
        SpUtil.setOrder(null);
        imgScan.setVisibility(View.VISIBLE);
        imgScanContent.setVisibility(View.VISIBLE);
        arlWave.setVisibility(View.GONE);
        tvFinishTime.setVisibility(View.GONE);
    }

    /**
     * 查询进行中的订单
     */
    @Subscribe(code = EventCode.GET_STATUS_ORDER)
    public void getStatusOrder(){
        setWasherTimer();
        presenter.getOrderInfo();
    }
    @Subscribe(code = EventCode.FINISH_WASHER)
    public void finishWasher(){
        waveView.change(1);
        imgScan.setVisibility(View.VISIBLE);
        imgScanContent.setVisibility(View.VISIBLE);
        arlWave.setVisibility(View.GONE);
        tvFinishTime.setVisibility(View.GONE);
    }

    public void setWasherTimer(){
        if (SpUtil.getUser() == null){
            //当前已经退出登录
            notOrder();
        }
        OrderInfo order = SpUtil.getOrder();
        if (order == null){
            notOrder();
            return;
        }
        int min = order.getRestTime();
        tvRestTime.setText(min+"");
        imgScan.setVisibility(View.GONE);
        imgScanContent.setVisibility(View.GONE);
        arlWave.setVisibility(View.VISIBLE);
        tvFinishTime.setText("预计洗衣结束时间:"+ DateUtils.getWasherFinishiTime(min));
        tvFinishTime.setVisibility(View.VISIBLE);
        double w = ((double) order.getProgressTime())/order.getPatternTime();
        waveView.change(w);
    }

}
